<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Model\ChenAppointment as Model;
use App\Models\Admin;
use App\Models\NewPrecut;
use App\Models\NewPrecutAssign;
use App\Models\NewPrecutCoverage;
use App\Models\NewPrecutPart;
use App\Models\NewPrecutFpart;
use App\Models\Warranty;
use App\Services\ModuleService;
use App\Services\UserService;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpWord\PhpWord;

class NewPrecutController extends Controller
{

    /*
     * index*/
    public function index(Request $request)
    {
        $admin_id = gui();
        $user_type = gut();

        $admin = Admin::find($admin_id);
        if ($user_type == 2) {
            return $this->index_sd($request);
        } else {
            return $this->index_gly($request);
        }
    }

    public function index_gly(Request $request)
    {
        $page = [
            'page_name' => 'precut',
            'title' => ts('MANAGEPRECUT'),
        ];
        $model = DB::table('new_precut as p')
            ->leftJoin('new_precut_fpart as fp', function ($query) {
                $query->on('p.id', 'fp.precut_id')->whereNull('fp.deleted_at');
            })
            ->leftJoin('new_precut_coverage as fc', function ($query) {
                $query->on('p.id', 'fc.precut_id')->whereNull('fc.deleted_at');
            })
            ->leftJoin('warranty as w', function ($query) {
                $query->on('w.precut_id', 'p.id')->where('w.precut_id', '>', 0)
                    ->whereNull('w.deleted_at');
            })
            ->leftJoin('users as u', 'u.id', 'p.user_id')
            ->whereNull('p.deleted_at')
            ->where('p.type', 0)
            ->groupBy('p.id');
        $model = filterByColumns($model, ['p.precut_id', 'w.first_name', 'w.phone_number', 'u.abbr']);
        $model = filterByDateRange($model, 'p.created_at');
        # $model = NewPrecut::where('id', '>', 0);
        if ($request->input('status') !== null) {
            $status = (int) $request->input('status');
            if ($status == 2) {
                $model = $model->where(function ($query) {
                    $query->where('p.user_id', 0)
                        ->orWhereNull('p.user_id');
                });
            } else {
                $model = $model->where('p.user_id', '>', 0)
                    ->where('p.status', $status);
            }
        }
        if ($request->input('key') !== null) {
            $key = $request->input('key');
            $model = $model->where(function ($q) use ($key) {
                $q->where("p.precut_id", "like", "%" . $key . "%");
            });
        }
        if (session('admin.user_type') == 4) {
            $userService = new UserService();
            $distributions = $userService->getDistributions(4, session('admin.id'));
            $userIdArr = $distributions;
            if (!empty($distributions)) {
                $dealers = $userService->getDealers($distributions);
                $userIdArr = array_merge($userIdArr, $dealers);
            }

            $model->whereIn('p.user_id', $userIdArr ?: []);
        }


        $model = $model->select([
            'p.*',
            'w.first_name',
            'w.phone_number',
            'w.warranty_id',
            'fp.part_id',
            'fp.film_type_id',
            'fp.length',
            'u.abbr',
            DB::raw("GROUP_CONCAT(fc.roll_number, '：', fc.length, ' cm' separator '\n') as roll_numbers "),
        ])->orderByDesc('id');
        $data = $model->paginate(50);
        $menus = (new ModuleService())->getWebButton(session('admin.role_id') ?? 0, $request->path());

        return view('admin.new-precut.index-gly1', [
            'page' => $page,
            'data' => $data,
            'menus' => $menus,
        ]);
    }

    /*
     * 目前能看到所有创建的，以及分配给下属经销商的
     * 假如后期一旦分配出去就无法再看到，可以将查询语句p.created_by改为u.id*/
    public function index_sd(Request $request)
    {
        $admin_id = gui();
        $page = [
            'page_name' => 'precut',
            'title' => ts('MANAGEPRECUT'),
        ];
        $model = DB::table('new_precut as p')
            ->leftJoin('new_precut_fpart as fp', function ($query) {
                $query->on('p.id', 'fp.precut_id')->whereNull('fp.deleted_at');
            })
            ->leftJoin('new_precut_coverage as fc', function ($query) {
                $query->on('p.id', 'fc.precut_id')->whereNull('fc.deleted_at');
            })
            ->leftJoin('warranty as w', function ($query) {
                $query->on('w.precut_id', 'p.id')->where('w.precut_id', '>', 0)
                    ->whereNull('w.deleted_at');
            })
            ->leftJoin('users as u', 'u.id', 'p.user_id')
            ->whereNull('p.deleted_at')
            ->where('p.type', 0)
            ->where(function ($query) use ($admin_id) {
                $query->where('p.created_by', $admin_id)
                    ->orWhere('u.creator_id', $admin_id);
            })
            /*->where(function($query) use ($admin_id) {
                $query->where('p.user_id', $admin_id)
                    ->orWhere('p.created_by', $admin_id);
            })*/
            ->groupBy('p.id');
        $model = filterByColumns($model, ['p.precut_id', 'w.warranty_id', 'fc.roll_number', 'u.abbr']);
        $model = filterByDateRange($model, 'p.created_at');
        # $model = NewPrecut::where('id', '>', 0);
        if ($request->input('status') !== null) {
            $status = (int) $request->input('status');
            if ($status == 2) {
                $model = $model->where(function ($query) {
                    $query->where('p.user_id', 0)
                        ->orWhereNull('p.user_id');
                });
            } else {
                $model = $model->where('p.user_id', '>', 0)
                    ->where('p.status', $status);
            }
        }

        $model = $model->select([
            'p.*',
            'w.first_name',
            'w.phone_number',
            'w.warranty_id',
            'fp.part_id',
            'fp.film_type_id',
            'fp.length',
            'u.abbr',
            DB::raw("GROUP_CONCAT(fc.roll_number, '：', fc.length, ' cm' separator '\n') as roll_numbers "),
        ])->orderByDesc('id');
        $data = $model->paginate(50);
        $menus = (new ModuleService())->getWebButton(session('admin.role_id') ?? 0, $request->path());

        return view('admin.new-precut.index-sd', [
            'page' => $page,
            'data' => $data,
            'menus' => $menus,
        ]);
    }

    public function create()
    {

        $page = [
            'page_name' => 'precut',
            'title' => ts('ADDNEW'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEPRECUT'),
                    'url' => '/admin/new-precut/'
                ]
            ],
        ];
        $data = new NewPrecut();
        return view('admin.new-precut.vue-create', [
            'page' => $page,
            'data' => $data,
        ]);
        return view('admin.new-precut.create', [
            'page' => $page,
            'data' => $data,
        ]);
    }

    public function store()
    {
        return abort(404);
        $admin_id = gui();
        $admin_type = gut();
        $admin = gum();
    }
    public function edit()
    {
        return abort(404);
    }
    public function update()
    {
        return abort(404);
    }
    public function show(Request $request, $id)
    {
        $page = [
            'page_name' => 'precut',
            'title' => ts('XQ'),
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEPRECUT'),
                    'url' => '/admin/new-precut/'
                ]
            ],
        ];
        $model = NewPrecut::findOrFail($id);
        $warranty = Warranty::where([
            'precut_id' => $model->id
        ])->first();
        if (empty($warranty->id)) {
            $warranty = new Warranty();
        };
        $assign = NewPrecutAssign::where('precut_id', $model->id)
            ->get();
        $parts = NewPrecutFpart::where('precut_id', $model->id)
            ->get();
        $pvcs = NewPrecutCoverage::where('precut_id', $model->id)
            ->get();
        return view('admin.new-precut.show', [
            'page' => $page,
            'data' => $model,
            'warranty' => $warranty,
            'assign' => $assign,
            'parts' => $parts,
            'pvcs' => $pvcs,
        ]);
    }
    public function destroy(Request $request, $id)
    {
        return deleteNewPrecut($id);
    }
    public function deletes(Request $request)
    {
        $ids = $request->input('id');
        if (empty($ids)) {
            return ['status' => false, 'msg' => '参数错误！'];
        }
        foreach ($ids as $k => $id) {
            deleteNewPrecut($id);
        }
        return ['status' => 'SUCCESS', 'msg' => '专车专用套件信息删除成功！'];
    }
    /*
     * 导出套件
     * 套件ID、安装部位、用料长度、膜型号、卷号与长度*/
    public function export(Request $request)
    {
        set_time_limit(0);
        $admin_id = gui();
        $admin_type = gut();
        $model = DB::table('new_precut as p')
            ->leftJoin('new_precut_fpart as fp', function ($query) {
                $query->on('p.id', 'fp.precut_id')->whereNull('fp.deleted_at');
            })
            ->leftJoin('new_precut_coverage as fc', function ($query) {
                $query->on('p.id', 'fc.precut_id')->whereNull('fc.deleted_at');
            })
            ->leftJoin('warranty as w', function ($query) {
                $query->on('w.precut_id', 'p.id')->where('w.precut_id', '>', 0)
                    ->whereNull('w.deleted_at');
            })
            ->leftJoin('users as x', 'x.id', 'p.created_by')
            ->leftJoin('users as y', 'y.id', 'p.user_id')
            ->leftJoin('new_precut_part as g', 'g.id', 'fp.part_id')
            ->leftJoin('film_type_master as h', 'h.id', 'fp.film_type_id')
            ->select(
                [
                    'p.precut_id',
                    'fp.part_id',
                    'fp.film_type_id',
                    'fp.length',
                    DB::raw("g.simplified_chiness_value as part "),
                    DB::raw("h.simplified_chiness_value as filmType "),
                    DB::raw("GROUP_CONCAT(fc.roll_number, '：', fc.length, ' cm' separator '\n') as roll_numbers "),
                    DB::raw("x.abbr as created_name"),
                    DB::raw("x.abbr as user_name"),
                    'p.status',
                    DB::raw("IF(p.status=1, '已安装', '待安装') as status_name"),
                ]
            );
        if ($admin_type == 2) {
            $model->where(function ($query) use ($admin_id) {
                $query->where('p.created_by', $admin_id)
                    ->orWhere('p.user_id', $admin_id)
                    ->orWhere('x.creator_id', $admin_id);
            });
        }

        /*DB::raw("GROUP_CONCAT(g.simplified_chiness_value separator '\n') as part "),
        DB::raw("GROUP_CONCAT(h.simplified_chiness_value separator '\n') as filmType "),*/

        /*$model = filterByColumns($model, [
            'p.precut_id',
            'w.warranty_id',
            'w.phone_number',
            'w.first_name',
            // 'w.license_plate',
            // 'w.dealer_name',
            // 'w.installer_name',
            // 'w.dealer_name',
            // 'u.abbr',
            // 'u.company_name',
            'y.abbr',
            'pf.roll_number'
        ]);*/

        /*$model = filterByDateRange($model, 'w.installation_date');

        if ($request->input('status') !== null) {
            $model = $model->where('w.approved', $request->input('status'));
        }*/
        // if ($request->input('status') !== null) {
        //     $status = (int) $request->input('status');
        //     if ($status == 2) {
        //         $model = $model->where("p.status", "=", 2);
        //     } else {
        //         $model = $model->where("p.status", "=", $status);
        //     }
        // }
        $model = filterByColumns($model, ['p.precut_id', 'w.warranty_id', 'fc.roll_number'],"key");
        $model = filterByDateRange($model, 'p.created_at');
        # $model = NewPrecut::where('id', '>', 0);
        if ($request->input('status') !== null) {
            $status = (int) $request->input('status');
            if ($status == 2) {
                $model = $model->where(function ($query) {
                    $query->where('p.user_id', 0)
                        ->orWhereNull('p.user_id');
                });
            } else {
                $model = $model->where('p.user_id', '>', 0)
                    ->where('p.status', $status);
            }
        }
        $data = $model->orderByDesc('p.id')
            ->where('p.type', 0)
            ->groupBy('p.id')
            ->get();
        $fields = [
            'precut_id' => '套件ID',
            'part' => '安装部位',
            'length' => '用料长度',
            'filmType' => '膜型号',
            'roll_numbers' => '卷号与长度',
        ];
        $uploads = [];
        foreach ($data as $k => $v) {
            // $v->filmType = ts('film_type_master.'.$v->film_type_id);
            // $v->part = ts('new_precut_master.'.$v->part_id);
            $item = [];
            foreach ($fields as $f => $m) {
                $item[] = [
                    'label' => $m,
                    'value' => $v->$f
                ];
            }
            $uploads[] = $item;
        }

        return makeExcel($uploads, '专车专用套件');
    }
}
